package it.uniroma2.imagetranscoder;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.yammer.metrics.Meter;
import com.yammer.metrics.Timer;

@SuppressWarnings("serial")
public class UploadServlet extends HttpServlet {
	
	private Meter serviceRate = WebAppContextListener.mRegistry.meter("serviceRate");
	private Timer processingDuration = WebAppContextListener.mRegistry.timer("processing-duration");
	
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		InputStream filecontent = null;
		Timer.Context context = processingDuration.time();
		try {
			@SuppressWarnings("unchecked")
			List<FileItem> items = new ServletFileUpload(
					new DiskFileItemFactory()).parseRequest(request);
			ImageTranscoder imageTranscoder = new ImageTranscoder();
			
			NioTransferCopy nioTransferCopy = new NioTransferCopy(getClass().getClassLoader().getResource("").getFile());
			
			int filterToApply = -1;
			for (FileItem item : items) {
				if (item.isFormField()) {
					// Process regular form field (input
					// type="text|radio|checkbox|etc", select, etc).
					if (item.getFieldName().equals("filter")) {
						filterToApply = Integer.parseInt(item.getString());
					}
				} else {
					// Process form file field (input type="file").
					filecontent = item.getInputStream();

				    File fileOut = new File(getClass().getClassLoader().getResource("").getFile()+File.separator+"fileOut_"+UUID.randomUUID().toString()+"_"+System.currentTimeMillis()+".tmp");
				   
				    File fileIn = nioTransferCopy.inputstreamToFile(filecontent);
					nioTransferCopy.nioTransferCopy(fileIn, fileOut);
					fileIn.delete();
					fileOut.delete();

					response.setContentType("text/html");
					response.getWriter().println("YesYouCan");
					
					response.setStatus(200);
					
					//if you want to transfer the image 
					//ImageIO.write(imageResponse.getBufferedImage(), imageResponse.getExt(), out);
					
				}
			}
			serviceRate.mark();
		} catch (FileUploadException e) {			
			throw new ServletException("Cannot parse multipart request.", e);
		}finally{
			context.stop();
			if(filecontent !=null){
				filecontent.close();
			}
		}
	}

	
	
	private String getLength(File file){
	    long size = file.length()/1024;
        String dim = size+ " KB";
        if (size > 1024) {
        	size/=1024L;
        	dim = size + " MB";
        }
        if (size >= 1024) {
        	size/=1024L;
        	dim = size + " GB";
        	
        }
        return dim;
	}

}
